package com.kfm.jdbc.day01;

import java.sql.*;

public class Demo09 {

    public static void main(String[] args) {
        Emp empById = getEmpById(7369);
        System.out.println(empById);
    }


    public static Emp getEmpById(Integer empno) {
        String url = "jdbc:mysql://localhost:3306/scott";
        String user = "root";
        String pass = "root";

        /*
               1. 注册驱动
               2. 创建连接
               3. 创建 PreparedStatement 对象
               4. 设置参数
               5. 执行操作
               6. 解析结果
               7. 释放资源
         */

        String sql = "select * from emp where empno = ?";
        ResultSet resultSet = null;
        try (
                // 创建连接
                Connection conn = DriverManager.getConnection(url, user, pass);
                // 创建 PreparedStatement 对象
                PreparedStatement preparedStatement = conn.prepareStatement(sql)
        ) {
            // 设置参数
            preparedStatement.setObject(1, empno);

            // 执行操作
            resultSet = preparedStatement.executeQuery();

            // 元数据
            ResultSetMetaData metaData = resultSet.getMetaData();


            // 解析结果
            while (resultSet.next()) {
                Emp emp = new Emp();
                // 获取列
                emp.setEmpno(resultSet.getInt("empno"));
                emp.setEname(resultSet.getString("ename"));
                emp.setJob(resultSet.getString("job"));
                emp.setMgr(resultSet.getInt("mgr"));
                emp.setHiredate(resultSet.getDate("hiredate"));
                emp.setSal(resultSet.getDouble("sal"));
                emp.setComm(resultSet.getDouble("comm"));
                emp.setDeptno(resultSet.getInt("deptno"));
                return emp;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        return null;
    }
}
